//
//  HEPickerView.m
//  HealthFamily
//
//  Created by LOOK on 2020/12/27.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEPickerView.h"

/// 标题栏高度（包括确定/取消，和年/月/日）
#define kTitleBarViewHeight 84

#define kBottomBtnViewHeight 49
/// 滚轮选择器的高度
#define kPickerViewHeight 167
/// 主题颜色
#define kThemeColor [UIColor blueColor]

@interface HEPickerView ()<UIPickerViewDataSource, UIPickerViewDelegate>

// 蒙层视图
@property (nonatomic, strong) UIView *maskView;

// 弹出背景视图
@property (nonatomic, strong) UIView *alertView;

// 标题栏背景视图
@property (nonatomic, strong) UIView *titleBarView;

// 中间标题
@property (nonatomic, strong) UILabel *titleLabel;

// 底部按钮
@property (nonatomic, strong) UIView *bottomBarView;

/** 日期选择器 */
@property (nonatomic, strong) UIPickerView *pickerView;

@property (nonatomic, strong) NSMutableArray *selectArr;

@end

@implementation HEPickerView

- (NSMutableArray *)selectArr {
    if (!_selectArr) {
        _selectArr = [NSMutableArray array];
    }
    return _selectArr;
}

- (void)initSelectModel {
    [self.selectArr removeAllObjects];
    
    for (int i = 0; i < _dataSource.count; i++) {
        NSArray *culms = _dataSource[i];
        HEPickerResModel *model = [HEPickerResModel new];
        model.compent = i;
        model.row = 0;
        model.value = culms[0];
        [self.selectArr addObject:model];
    }
}

/// 设置选中值
- (void)setupSelectValue {
    for (int i = 0; i < _selectValues.count; i++) { // 列
        NSString *value = _selectValues[i];
        NSArray *rows = _dataSource[i];
        HEPickerResModel *model = self.selectArr[i];

        for (int j = 0; j < rows.count; j++) { // 行
            NSString *rowValue = rows[j];
            if ([value isEqualToString: rowValue]) {
                model.row = j;
                model.value = rowValue;
                [self.pickerView selectRow:j inComponent:i animated:NO];
                break;
            }
        }
    }
}

- (void)show {
    
    [self initSelectModel];
    [self initUI];
    
    
    // 添加日期选择器
    [self.alertView addSubview:self.pickerView];
    [self.pickerView reloadAllComponents];
    // 默认滚动的行
    [self setupSelectValue];

    
    UIWindow *keyWindow = BRGetKeyWindow();
    [keyWindow addSubview:self];
    // 动画前初始位置
    CGRect rect = self.alertView.frame;
    rect.origin.y = self.bounds.size.height;
    self.alertView.frame = rect;
    // 弹出动画
    self.maskView.alpha = 1;
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = self.alertView.frame;
        rect.origin.y -= kPickerViewHeight + kTitleBarViewHeight + BR_BOTTOM_MARGIN + kBottomBtnViewHeight;
        self.alertView.frame = rect;
    }];
}

- (void)initUI {
    self.frame = [UIScreen mainScreen].bounds;
    // 设置子视图的宽度随着父视图变化
    self.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    [self addSubview:self.maskView];
    
    [self addSubview:self.alertView];
    [self.alertView addSubview:self.titleBarView];
    [self.titleBarView addSubview:self.titleLabel];
    [self.alertView addSubview:self.bottomBarView];
}

#pragma mark -
#pragma mark - 蒙层视图
- (UIView *)maskView {
    if (!_maskView) {
        _maskView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _maskView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2f];
        // 设置子视图的大小随着父视图变化
        _maskView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _maskView.userInteractionEnabled = YES;
        UITapGestureRecognizer *myTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapMaskView:)];
        [_maskView addGestureRecognizer:myTap];
    }
    return _maskView;
}

#pragma mark - 弹框视图
- (UIView *)alertView {
    if (!_alertView) {
        _alertView = [[UIView alloc]initWithFrame:CGRectMake(0, self.bounds.size.height - kTitleBarViewHeight - kPickerViewHeight - kBottomBtnViewHeight - BR_BOTTOM_MARGIN, self.bounds.size.width, kTitleBarViewHeight + kPickerViewHeight + BR_BOTTOM_MARGIN + kBottomBtnViewHeight)];
        _alertView.backgroundColor = [UIColor whiteColor];
        _alertView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
    }
    return _alertView;
}

#pragma mark - 标题栏视图
- (UIView *)titleBarView {
    if (!_titleBarView) {
        _titleBarView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, kTitleBarViewHeight)];
        _titleBarView.backgroundColor = [UIColor whiteColor];
        _titleBarView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        // 设置标题栏底部分割线
//        UIView *titleLineView = [[UIView alloc]initWithFrame:CGRectMake(0, 44 - 0.5f, _titleBarView.frame.size.width, 0.5f)];
//        titleLineView.backgroundColor = BR_RGB_HEX(0xdadada, 1.0f);
//        titleLineView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
//        [_titleBarView addSubview:titleLineView];
        
         NSMutableArray *arr = @[].mutableCopy;
        
        for (NSString *str in _subTitles) {
            UILabel *yearLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 44, self.alertView.frame.size.width / 3, 44)];
            yearLabel.backgroundColor = [UIColor whiteColor];
            yearLabel.textColor = [UIColor darkGrayColor];
            yearLabel.font = [UIFont systemFontOfSize:16.0f];
            yearLabel.textAlignment = NSTextAlignmentCenter;
            yearLabel.text = str;
            [_titleBarView addSubview:yearLabel];
            [arr addObject:yearLabel];
        }
        
        [arr mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_titleBarView).offset(44);
            make.height.offset(40);
        }];
        [arr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:0 tailSpacing:0];
    }
    return _titleBarView;
}

#pragma mark - 中间标题label
- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 44)];
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = DYBlodFont(16);
        _titleLabel.textColor = [UIColor darkGrayColor];
        _titleLabel.text = self.title;
    }
    return _titleLabel;
}

#pragma mark - 底部按钮
- (UIView *)bottomBarView {
    if (!_bottomBarView) {
        _bottomBarView = [[UIView alloc] init];
        [self.alertView addSubview:_bottomBarView];
        
        _bottomBarView.qmui_borderPosition = QMUIViewBorderPositionTop;
        _bottomBarView.qmui_borderWidth = 1;
        _bottomBarView.qmui_borderColor = CSplitLineColor;
        
        [_bottomBarView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.left.right.equalTo(self.alertView);
            make.height.offset(kBottomBtnViewHeight);
        }];
        
        UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [cancelBtn setTitleColor:CNavBgColor forState:UIControlStateNormal];
        cancelBtn.titleLabel.font = DYFont(16);
        [_bottomBarView addSubview:cancelBtn];
        [cancelBtn addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];

        UIButton *comfireBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [comfireBtn setTitle:@"确认" forState:UIControlStateNormal];
        [comfireBtn setTitleColor:KWhiteColor forState:UIControlStateNormal];
        comfireBtn.backgroundColor = CNavBgColor;
        comfireBtn.titleLabel.font = DYFont(16);
        [_bottomBarView addSubview:comfireBtn];
        [comfireBtn addTarget:self action:@selector(comfireClick) forControlEvents:UIControlEventTouchUpInside];

        NSMutableArray *arr = @[cancelBtn, comfireBtn].mutableCopy;
        [arr mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_bottomBarView).offset(1);
            make.bottom.equalTo(_bottomBarView);
        }];
        [arr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:0 tailSpacing:0];
    }
    return _bottomBarView;
}


#pragma mark - 选择器
- (UIPickerView *)pickerView {
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, kTitleBarViewHeight, self.bounds.size.width, kPickerViewHeight)];
        _pickerView.backgroundColor = [UIColor whiteColor];
        _pickerView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
        _pickerView.dataSource = self;
        _pickerView.delegate = self;
    }
    return _pickerView;
}

#pragma mark - 点击蒙层视图事件
- (void)didTapMaskView:(UITapGestureRecognizer *)sender {
    [self dismiss];
}

#pragma mark - 关闭选择器视图
- (void)dismiss {
    // 关闭动画
    [UIView animateWithDuration:0.2 animations:^{
        CGRect rect = self.alertView.frame;
        rect.origin.y += kPickerViewHeight + kTitleBarViewHeight + BR_BOTTOM_MARGIN + kBottomBtnViewHeight;
        self.alertView.frame = rect;
        self.maskView.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma mark - 取消按钮关闭视图
- (void)cancelClick {
    [self dismiss];
}

- (void)comfireClick {
    if (self.resultModelArrayBlock) {
        self.resultModelArrayBlock(self.selectArr);
    }
    [self dismiss];
}


#pragma mark - UIPickerViewDataSource
// 1. 设置 picker 的列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return _subTitles.count;
}

// 2. 设置 picker 每列的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    NSArray *rowsArr = _dataSource[component];
    return rowsArr.count;
}

#pragma mark - UIPickerViewDelegate
// 3. 设置 picker 的 显示内容
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view {
    
    // 设置分割线的颜色
    for (UIView *subView in pickerView.subviews) {
        if (subView && [subView isKindOfClass:[UIView class]] && subView.frame.size.height <= 1) {
            subView.backgroundColor = [UIColor colorWithRed:195/255.0 green:195/255.0 blue:195/255.0 alpha:1.0];
        }
    }
    
    UILabel *label = (UILabel *)view;
    if (!label) {
        label = [[UILabel alloc]init];
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:18.0f];
        label.textColor = [UIColor blackColor];
        // 字体自适应属性
        label.adjustsFontSizeToFitWidth = YES;
        // 自适应最小字体缩放比例
        label.minimumScaleFactor = 0.5f;
    }
    
    // 给选择器上的label赋值
    NSArray *rowsArr = _dataSource[component];
    label.text = rowsArr[row];
    
    return label;
}

// 4. 日期选择器 每次滚动后的回调方法
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    for (HEPickerResModel *model in self.selectArr) {
        if (model.compent == component) {
            NSArray *rowsArr = _dataSource[component];
            model.row = row;
            model.value = rowsArr[row];
            break;
        }
    }
}

// 设置行高
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 35.0f;
}

@end
